<template>
    <van-icon
      :color="isCollected ? '#ffa500' : '#777'"
      :name="isCollected ? 'star' : 'star-o'"
      :loading="collectLoading"
      @click="onCollect"
    />
</template>

<script>
import { addCollectAPI, deleteCollectAPI } from '../../../api/index.js'
export default {
  name: 'CollectArticle',
  props: {
    isCollected: {
      type: Boolean,
      default: false
    },
    articleId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      collectLoading: false // 收藏按钮加载状态
    }
  },
  methods: {
    // 收藏，取消收藏用户
    async onCollect () {
      let message = '操作成功'
      try {
        // 调用接口前开启加载
        this.collectLoading = true
        if (this.isCollected) {
          // 已收藏，需要取消收藏
          await deleteCollectAPI(this.articleId)
          message = '取消收藏成功'
        } else {
          // 未收藏，需要添加收藏
          await addCollectAPI({
            target: this.articleId
          })
          message = '收藏成功'
        }
        // this.$emit('changeIsFollowed', !this.isFollowed)
        this.$emit('update:isCollected', !this.isCollected)
        this.$toast.success(message)
      } catch (error) {
        console.log(error)
        message = '网络异常，请稍后重试'
        this.$toast.fail(message)
      }

      // 无论成功还是失败都需要关闭加载状态
      this.collectLoading = false
    }
  }
}
</script>

<style>

</style>
